import React, { useEffect, useState, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Spin } from 'antd';
import { useAuthStore } from '@/stores/authStore';
import { Layout } from '@/components';
import { ProtectedRoutes } from '@/utils/routeManager';

// 登录页面懒加载
const Login = React.lazy(() => import('@/pages/Login'));

// 路由守卫组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated, user, token } = useAuthStore();
  
  console.log('🛡️ ProtectedRoute check:', { isAuthenticated, hasUser: !!user, hasToken: !!token });
  
  if (!isAuthenticated) {
    console.log('❌ 未认证，重定向到登录页');
    return <Navigate to="/login" replace />;
  }
  
  console.log('✅ 认证通过，显示受保护的内容');
  return <>{children}</>;
};

// 应用初始化组件
const AppInitializer: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isInitializing, setIsInitializing] = useState(true);
  const { checkAuth, token, isAuthenticated, user } = useAuthStore();

  useEffect(() => {
    const initializeAuth = async () => {
      console.log('🚀 应用初始化开始:', { hasToken: !!token, isAuthenticated });
      
      if (token) {
        console.log('🔍 检查token有效性...');
        try {
          const result = await checkAuth();
          console.log('✅ 认证检查结果:', result);
        } catch (error) {
          console.error('❌ 认证检查失败:', error);
        }
      } else {
        console.log('❌ 没有token，跳过认证检查');
      }
      
      // 获取最新状态
      const finalState = useAuthStore.getState();
      console.log('🏁 初始化完成，最终状态:', {
        isAuthenticated: finalState.isAuthenticated,
        hasUser: !!finalState.user,
        hasToken: !!finalState.token,
      });
      
      setIsInitializing(false);
    };

    initializeAuth();
  }, [checkAuth, token]);

  if (isInitializing) {
    console.log('⏳ 应用初始化中...');
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Spin size="large" tip="初始化应用中..." />
      </div>
    );
  }

  console.log('✅ 应用初始化完成，渲染子组件');
  return <>{children}</>;
};

const App: React.FC = () => {
  return (
    <div className="App">
      <AppInitializer>
        <Routes>
          {/* 登录页面 */}
          <Route 
            path="/login" 
            element={
              <Suspense fallback={
                <div className="min-h-screen flex items-center justify-center">
                  <Spin size="large" tip="加载中..." />
                </div>
              }>
                <Login />
              </Suspense>
            } 
          />
          
          {/* 受保护的路由 */}
          <Route
            path="/*"
            element={
              <ProtectedRoute>
                <Layout>
                  <Suspense fallback={
                    <div className="flex items-center justify-center min-h-[200px]">
                      <Spin size="large" tip="页面加载中..." />
                    </div>
                  }>
                    <ProtectedRoutes />
                  </Suspense>
                </Layout>
              </ProtectedRoute>
            }
          />
        </Routes>
      </AppInitializer>
    </div>
  );
};

export default App; 